package com.platform.study.thread;

/**
 * 用实现Runnable接口方式实现线程:线程同步
 * User: wangyanginfo
 * Date: 12-11-26
 * Time: 下午2:44
 */
public class RunnableSimple_8 implements Runnable {

    private int ticket = 10;  //10张票

    private Object lock = new Object();

    @Override
    public void run() {
        for (int i = 0; i < 60; i++) {
            correctMethod1();
        }
    }

    /**
     * 下面的方法会造成票数为负数
     */
    private void errorMethod() {
        if (ticket > 0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 运行 _  " + ticket--);
        }
    }

    /**
     * 下面的方法正确处理同步过程 synchronized
     */
    private synchronized void correctMethod() {
        if (ticket > 0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 运行 _  " + ticket--);
        }
    }

    /**
     * 下面的方法正确处理同步过程 synchronized块
     */
    private void correctMethod1() {
        synchronized (lock) {
            if (ticket > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 运行 _  " + ticket--);
            }
        }
    }

    public static void main(String[] args) {
        RunnableSimple_8 simpleA = new RunnableSimple_8();
        Thread thread1 = new Thread(simpleA, "线程1");
        Thread thread2 = new Thread(simpleA, "线程2");
        Thread thread3 = new Thread(simpleA, "线程3");
        thread1.start();
        thread2.start();
        thread3.start();
    }

}
